import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:u_push_plugin/data.dart';

class UPushPlugin {
  static String _deviceToken;
  static const MethodChannel _channel = const MethodChannel('u_push_plugin');
  static const EventChannel _eChannel = const EventChannel('u_push_plugin_e');
  static ValueChanged<LoginData> _loginListener;
  static ValueChanged<Map> _messageListener;
  static ValueChanged<Map> _receiveListener;
  static bool _showLog = true;
  static const Tag = "SL_UPush";

  ///前台是否推送
  static Future showNotificaitonOnForeground({bool show = false}) async {
    await _channel.invokeMethod("showNotificaitonOnForeground", {"show": show});
  }

  ///勿打扰时间
  static Future setNoDisturbMode({
    int startHour = 0,
    int endHour = 0,
    int startMin = 0,
    int endMin = 0,
  }) async {
    await _channel.invokeMethod("setNoDisturbMode", {
      "startHour": startHour,
      "endHour": endHour,
      "startMin": startMin,
      "endMin": endMin,
    });
  }

//  ///添加标签
//  static Future addTags(List<String> tags) async {
//    var value = await _channel.invokeMethod("addTag", {"tags": tags});
//    if(showLog){
//      print(value);
//    }
//    return value;
//  }
//
//  ///删除标签
//  static Future deleteTags(List<String> tags) async {
//    var value = await _channel.invokeMethod("deleteTags", {"tags": tags});
//    print(value);
//    return value;
//  }
//
//  ///获取全部标签
//  static Future getTags() async {
//    var value = await _channel.invokeMethod("getTags");
//    print(value);
//    return value;
//  }
//
//  ///增加别名
//  static Future addAlias(String alias, String type) async {
//    var value =
//        await _channel.invokeMethod("addAlias", {"alias": alias, "type": type});
//    print(value);
//    return value
//  }
//
//  ///设置别名
//  static Future setAlias(String alias, String type) async {
//    var value =
//        await _channel.invokeMethod("setAlias", {"alias": alias, "type": type});
//    print(value);
//    return value;
//  }
//
//  ///删除别名
//  static Future deleteAlias(String alias, String type) async {
//    var value = await _channel
//        .invokeMethod("deleteAlias", {"alias": alias, "type": type});
//    print(value);
//    return value;
//  }

  ///获取设备deviceToken
  static Future getDeviceToken() async {
    var value = await _channel.invokeMethod("getDeviceToken");
    print("设备deviceToken:$value");
    return value;
  }

  ///打开消息推送
  static Future<ToggleData> openPush() async {
    var value = await _channel.invokeMethod("openPush");
    var map = value["data"];
    return ToggleData(map["success"], map["message"]);
  }

  ///关闭消息推送
  static Future<ToggleData> closePush() async {
    var value = await _channel.invokeMethod("closePush");
    var map = value["data"];
    return ToggleData(map["success"], map["message"]);
  }

  ///获取缓存数据
  static Future<Map<dynamic, dynamic>> getCacheMessage() async {
    Map<dynamic, dynamic> value =
        await _channel.invokeMethod("getCacheMessage");
    if (_showLog) {
      print("aaaaaa  $Tag:$value");
    }

    Map<dynamic, dynamic> messageData = value["data"];
    return messageData;
  }

  ///执行监听器
  static initMessageListener() {
    _eChannel.receiveBroadcastStream().listen((event) {
      Map messageData = event["data"];

      print("messageData is ${messageData}");
      print("eventtype is ${event["type"]}");

      switch (event["type"]) {
        case 101: //登录
          LoginData data = LoginData(messageData);
          _deviceToken = data.code == 1 ? data.message : "";
          _loginListener?.call(data);
          break;
        case 102:
          _messageListener?.call(messageData);
          break;
        case 103:
          _receiveListener?.call(messageData);
          break;
      }
    });
  }

  ///注册登录监听
  static initRegisterListener(ValueChanged<LoginData> loginListener) {
    _loginListener = loginListener;
  }

  ///注册消息监听
  static initMessageResultListener(ValueChanged<Map> messageListener) {
    _messageListener = messageListener;
  }

  static initMessageReceiverListener(ValueChanged<Map> messageListener){
    _receiveListener = messageListener;
  }

  //当前设备添加tags
  static Future<AddTagResult> addTags(List<String> tags) async {
    var value = await _channel.invokeMethod("addTags", {"tags": tags});
    var map = value["data"];
    if (_showLog) {
      print("$Tag：$value");
    }
    return AddTagResult(map["remain"], map["success"], map["message"]);
  }

  //删除当前设备的tags
  static Future<AddTagResult> deleteTags(List<String> tags) async {
    var value = await _channel.invokeMethod("deleteTags", {"tags": tags});
    var map = value["data"];
    if (_showLog) {
      print("$Tag：$value");
    }
    return AddTagResult(map["remain"], map["success"], map["message"]);
  }

  //获取当前设备已经绑定的tags
  static Future<GetTagsResult> getTags() async {
    var value = await _channel.invokeMethod("getTags");
    var map = value["data"];
    if (_showLog) {
      print("$Tag：$value");
    }
    return GetTagsResult(
        map["tags"], map["message"] ?? "Android", map["remain"] ?? 0);
  }

  //添加别名
  static Future<Map<dynamic, dynamic>> addAlias(
      String aliasId, String aliasType) async {

    print("addAlias result 执行了");
    final Map<dynamic, dynamic> result = await _channel
        .invokeMethod("addAlias", {"aliasId": aliasId, "aliasType": aliasType});

    print("addAlias result is ${result}");

    if (_showLog) {
      print("$Tag：$result");
    }
    return result;
  }

  //重置别名
  static Future<Map<dynamic, dynamic>> setAlias(
      String aliasId, String aliasType) async {
    final Map<dynamic, dynamic> result = await _channel
        .invokeMethod("setAlias", {"aliasId": aliasId, "aliasType": aliasType});
    if (_showLog) {
      print("$Tag：$result");
    }
    return result;
  }

  //删除别名
  static Future<Map<dynamic, dynamic>> deleteAlias(
      String aliasId, String aliasType) async {
    final Map<dynamic, dynamic> result = await _channel.invokeMethod(
        "deleteAlias", {"aliasId": aliasId, "aliasType": aliasType});
    if (_showLog) {
      print("$Tag：$result");
    }
    return result;
  }

  //调试信息输出控制
  static void UMSetLogEnabled(bool logEnabled) {
    if (!Platform.isIOS) {
      return;
    }
    final Map<dynamic, dynamic> map = {"logEnabled": logEnabled};
    _channel.invokeMethod("UMSetLogEnabled", map);
  }

  ///flutter 展示输出
  static void changeFlutterLog(bool showLog) {
    _showLog = showLog;
  }

  //mark:-----------------------下面是iOS专属的方法------------------------

  ///ios初始化
  // appKey：申请的值
  // channel：通道的名字
  //logEnabled：默认false(不输出log); 设置为true, 输出可供调试参考的log信息. 发布产品时必须设置为false.
  //badgeClear：否开启角标清空
  static void UMInitIOS(String appKey,
      {String channel, bool logEnabled = false, bool badgeClear = true}) async {
    if (!Platform.isIOS) {
      return;
    }
    final Map<dynamic, dynamic> map = {
      "appkey": appKey,
      "channel": channel,
      "logEnabled": logEnabled,
      "badgeClear": badgeClear
    };
    _channel.invokeMethod("UMInitIOS", map);
  }

  //是否开启sdk自动清空角标（默认开）
  static void UMSetBadgeClear(bool debgeClear) {
    if (!Platform.isIOS) {
      return;
    }
    final Map<dynamic, dynamic> map = {"debgeClear": debgeClear};
    _channel.invokeMethod("UMSetBadgeClear", map);
  }
}

class ToggleData {
  bool success;
  String message;

  ToggleData(this.success, this.message);

  @override
  String toString() {
    return 'ToggleData{success: $success, message: $message}';
  }
}

class AddTagResult extends ToggleData {
  int remain; //剩余可用的tag数,为-1时表示异常

  AddTagResult(this.remain, bool success, String message)
      : super(success, message);
}

class GetTagsResult {
  List tags;
  String message;
  int remain;

  GetTagsResult(this.tags, this.message, this.remain);
}
